<template>
	<view class="ys" v-else>
		<view class="chatlist">
			<view class="chatscroll">
				<view class="chatlength">
					<view class="more_text" v-show="allow_refresh">下拉加载更多</view>
					<view :class="item.say_type == 1?'chatitem mychat':'chatitem '" v-for="(item,index) in chatList"
						:key="index" :id="'tab'+item.id">
						<image class="headerimg" :src="item.head_url || '/static/img/logo.png'" mode=""></image>
						<view class="item-info">
							<view class="name">
								{{item.name}} <text>{{item.add_time}}</text>
							</view>
							<view class="item-msg" v-if="item.type == 1">
								<text>{{item.content}}</text>
							</view>
							<view class="item-imgbox" v-else-if="item.type == 2">
								<image :src="item.img" mode="heightFix" @click="bigImg(item.img)">
								</image>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="sendmsg">
			<view class="top">
				<view class="imgbox emo">
					<image @click="openEx" src="/static/bq.png" mode="widthFix"></image>
				</view>
				<textarea v-model="content" :style="minHeight" @linechange="changeLine" @focus="closeEx"></textarea>
				<view class="imgbox">
					<image v-if="content == ''" @click="uploadImg" src="/static/add.png" mode="widthFix"></image>
				</view>
				<text v-if="content != ''" @click="sendMsg">发送</text>
			</view>
			<view class="emoji">
				<emoKeyboard :show="show_ex" :data="EmojiData" @change="change" @delMsg="delMsg"></emoKeyboard>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getChat,
		sendMsg,
		updateUnread
	} from "@/api/user.js"
	import {
		UserIndex
	} from "@/api/api.js"
	import emoKeyboard from '@/components/emoji/emoKeyboard.vue';
	export default {
		data() {
			return {
				websocket_url: '',
				room_id: '',
				store_id: '',
				content: '',
				chatList: [],
				temp_list: [],
				page: 1,
				total_page: 1,
				last_new_id: '',
				img_url: '',
				img_url_show: '',
				scrollView: 'tab',
				user_id: '',
				triggered: false,
				_freshing: false,
				allow_refresh: true,
				is_init: true,
				last_id: '',
				minHeight: '',
				show_ex: false,
				//表情可以去这里复制https://geekerline.com/emoji/
				EmojiData: [
					"😀", "😃", "😄", "😁", "😆", "😅", "😂", "🤣", "😊", "😇", "🙂", "🙃", "😉", "😌", "😍", "🥰",
					"😘", "😗", "😙", "😚", "😋", "😛", "😝", "😜", "🤪", "🤨", "🧐", "🤓", "😎", "🤩", "🥳", "😏",
					"😒", "😞", "😔", "😟", "😕", "🙁", "😣", "😖", "😫", "😩", "🥺", "😢", "😭", "😤", "😠", "😡",
					"🤬", "🤯", "😳", "🥵", "🥶", "😱", "😨", "😰", "😥", "😓", "🤗", "🤔", "🤭", "🤫", "🤥", "😶",
					"😐", "😑", "😬", "🙄", "😯", "😦", "😧", "😮", "😲", "😴", "🤤", "😪", "😵", "🤐", "🥴", "🤢",
					"🤮", "🤧", "😷", "🤒", "🤕", "🤑", "🤠", "😈", "👿", "👹", "👺", "🤡", "💩", "👻", "💀", "☠",
					"👽", "👾", "🤖", "🎃", "😺", "😸", "😹", "😻", "😼", "😽", "🙀", "😿", "😾"
				],
				is_connect: false,
				fail_count: 0,
				is_login: false,
				has_quan: false,
				is_open: false,
				user_id: '',
				socketTask: null
			}
		},
		components: {
			emoKeyboard
		},
		onUnload() {
			this.is_connect && uni.closeSocket({
				success(data) {
					console.log('WebSocket 关闭成功！');
				}
			})
		},
		onNavigationBarButtonTap(e) {

		},
		async onLoad(e) {

			let that = this
			let reqRes = await UserIndex()
			let reqData = reqRes.data
			this.is_login = true
			this.user_id = reqData.info.id
			this.websocket_url = reqData.websocket
			this.room_id = reqData.room_id
			this.getChat()
			// this.updateUnread()
			uni.closeSocket({
				success: () => {

				},
				fail: (err) => {
					console.log(err);
				}
			})
			if (!this.is_connect) {
				that.webSocket()
			}
		},
		onPageScroll(e) {
			if (e.scrollTop < 5) {
				if (!this.allow_refresh) {
					// uni.stopPullDownRefresh()
					uni.$showMsg('没有更多了')
					return false
				}
				this.onrefresh()
			}
		},
		methods: {
			webSocket() {
				var that = this
				if (this.is_connect) {
					return false
				}
				this.socketTask = uni.connectSocket({
					url: `${that.websocket_url}`,
					success: (res) => {
						console.log('连接成功', res)
					},
					fail: (err) => {
						console.log('链接失败', err);
					}
				});
				this.socketTask.onOpen(function(res) {
					uni.hideLoading()
					console.log('WebSocket连接已打开！');
					that.sendSocket('login', {
						type: "login",
						user_id: that.user_id,
						room_id: that.room_id
					})
					that.is_connect = true
				});
				this.socketTask.onError(function(res) {
					that.is_connect = false
					console.log('WebSocket连接打开失败，请检查！');
					that.fail_count++
					if (that.fail_count <= 7) {
						that.webSocket()
					}

				});
				this.socketTask.onClose(function(res) {
					that.is_connect = false
					console.log('WebSocket 已关闭！');
				});
				this.socketTask.onMessage(function(res) {
					let data = JSON.parse(res.data)
					console.log('收到服务器内容：', data, that.is_connect);
					if (data.type == 'ping') {
						return
					}
					if (data.status == 1) {
						let content = data.content
						if (data.type == 'message') {
							that.chatList.push(content.content)
							setTimeout(() => {
								that.scrollView = 'tab' + content.content.id
								uni.pageScrollTo({
									selector: `#${that.scrollView}`
								})
								console.log(that.scrollView);

							})
							that.updateUnread()
						}
					} else {
						uni.$showMsg(data.msg || '接收失败')
					}

				});
			},
			sendSocket(type, data = {}) {
				this.socketTask.send({
					data: JSON.stringify({
						type: type,
						data: data
					}),
					success(data) {

					},
					fail(err) {
						console.log('发送失败');
					}
				})
			},
			getChat(duration = 300) {
				let that = this
				getChat({
					room_id: that.room_id,
					page: that.page,
					last_new_id: that.last_new_id
				}).then(res => {
					that._freshing = false;
					that.triggered = false;
					uni.stopPullDownRefresh()
					if (res.status == 1) {
						let chatData = res.data.list.data
						if (that.page == 1) {
							var last_msg_id = ''
							if (chatData.length > 0) {
								that.last_new_id = chatData[chatData.length - 1].id
							}
						} else {
							var last_msg_id = that.chatList[0].id
						}
						that.chatList = [...chatData, ...that.chatList]
						that.last_page = res.data.last_page
						if (that.page < that.last_page) {
							that.allow_refresh = true
						} else {
							that.allow_refresh = false
						}
						if (that.chatList.length == 0) {
							return
						}
						that.$nextTick(() => {
							if (that.page == 1) {
								that.scrollView = 'tab' + that.chatList[that.chatList.length - 1].id
							} else {
								that.scrollView = 'tab' + last_msg_id
							}
							that.updateUnread() // 更新已读
							that.setPageScrollTo(`#${that.scrollView}`)
							// uni.pageScrollTo({
							// 	duration: 0,
							// 	selector: ,
							// 	success() {
							// 		console.log('滚动成功');
							// 	},
							// 	fail(err) {
							// 		console.log('滚动失败');
							// 	}
							// })
							if (that.page < res.data.last_page) {
								that.page++
							}
						})
					} else {
						return uni.$showMsg(res.message)
					}
				})
			},
			change(emoji) {
				this.content += emoji
			},
			delMsg() { //删除
				if (!this.content) return
				const lastTwoChars = this.content.slice(-2);
				if (this.isEmoji(lastTwoChars)) {
					this.content = this.content.substring(0, this.content.length - 2);
				} else {
					this.content = this.content.substring(0, this.content.length - 1);
				}
			},
			isEmoji(str) {
				// 匹配表情的正则表达式
				const regExp = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
				return regExp.test(str);
			},
			//k开关表情
			closeEx() {
				this.show_ex = false
			},
			openEx() {
				this.show_ex = !this.show_ex
			},
			//textarea高度
			changeLine(e) {
				let height = e.detail.height
				if (height < 40) {
					// #ifdef H5
					this.minHeight = 'min-height:auto'
					// #endif
					// #ifndef H5
					this.minHeight = 'min-height:40px'
					// #endif
				} else if (height < 80) {
					this.minHeight = 'min-height:' + height + 'px'
				}
			},

			setPageScrollTo(selector) {
				let view = uni.createSelectorQuery().in(this).select(selector);
				view.boundingClientRect((res) => {
					uni.pageScrollTo({
						scrollTop: res.top - 30, // -30 为多显示出大半个消息的高度，示意上面还有信息。
						duration: 0
					});
				}).exec();
			},
			async getChatList() {
				let that = this
				await getChatList({
					room_id: this.room_id,
					page: this.page
				}).then(res => {
					that._freshing = false;
					this.temp_list = res.data.chat.data
					// this.chatList = [...res.data.chat.data, ...this.chatList]
					this.total_page = res.data.chat.last_page
					this.last_id = this.temp_list[this.temp_list.length - 1].id

				})
			},
			onrefresh(e) {
				let that = this
				if (that._freshing) return;
				that._freshing = true;
				this.getChat(0)
				// setTimeout(() => {
				// 	that.triggered = false;
				// 	this.chatList = [...this.temp_list, ...this.chatList]
				// 	if (this.page < this.total_page) {
				// 		this.allow_refresh = true
				// 	} else {
				// 		this.allow_refresh = false
				// 	}
				// 	console.log('结束', that.triggered);
				// }, 500)
				// setTimeout(() => {
				// 	if (this.is_init) {
				// 		this.scrollView = 'tab' + this.last_id
				// 	}
				// 	console.log(this.scrollView);
				// }, 800)
			},
			updateUnread() {
				updateUnread({
					room_id: this.room_id
				}).then(res => {
					// if (res.code != 0) {
					// 	// uni.$showMsg(res.msg)
					// 	console.log('unread', res.message);
					// }
				})
			},

			toupper(e) {
				console.log(e);
				setTimeout(() => {
					this.scrollView = 'tab' + this.chatList[0].id
					console.log(this.scrollView);
				}, 50)
			},
			tobottom(e) {
				// console.log(e);
				// setTimeout(() => {
				// 	this.scrollView = 'tab' + this.chatList[this.chatList.length - 1].id
				// }, 50)
			},
			onpull(e) {
				// console.log('pull', e);
			},
			onstore(e) {
				this.triggered = 'restore'
				// console.log('onstore', e);
			},
			more() {
				let more = []
				// let lenght = more.length
				// this.$nextTick(() => {
				// 	this.scrollView = 's' + lenght
				// })
				// console.log(this.scrollView);
				this.chatList = [...more, ...this.chatList]
			},
			getHeight() {
				setTimeout(() => {
					let info = uni.createSelectorQuery().select('.chatlength')
					info.boundingClientRect(function(data) { //data - 各种参数
						console.log(data.height);
						uni.pageScrollTo({
							scrollTop: data.height
						})
					}).exec()
				})
			},
			bigImg(url) {
				let urls = [url]
				uni.previewImage({
					urls: urls
				})
			},
			sendSocketMessage(msg) {
				if (socketOpen) {
					uni.sendSocketMessage({
						data: msg
					});
				}
			},
			sendMsg() {
				console.log(this.is_connect);
				let that = this
				if (this.room_id === '') {
					return uni.$showMsg('房间不存在')
				}
				// if (!this.is_connect) {
				// 	uni.$showMsg('房间连接失败')
				// 	that.webSocket()
				// 	return false
				// }
				if (this.content == '' || this.content == undefined) {
					uni.$showMsg('内容无')
					return false
				}
				var content = this.content
				this.content = ''
				sendMsg({
					room_id: this.room_id,
					type: 1,
					content: content,
				}).then(res => {
					if (res.status == 1) {
						this.closeEx()
						let data = res.data
						this.chatList.push(data)
						setTimeout(() => {
							that.scrollView = 'tab' + res.data.id
							// that.setPageScrollTo(`#${that.scrollView}`)
							uni.pageScrollTo({
								duration: 100,
								selector: `#${that.scrollView}`,
								success() {
									console.log('滚动成功');
								},
								fail(err) {
									console.log('滚动失败');
								}
							})
						}, 100)
						let sendData = JSON.parse(JSON.stringify(res.data))
						sendData.say_type = 2
						this.sendSocket('send', {
							type: 1,
							content: sendData,
							room_id: that.room_id
						})

						// this.getHeight()
					} else {
						uni.$showMsg(res.message)
					}
				})
			},
			uploadImg() {
				let that = this
				uni.chooseImage({
					count: 1,
					success: (res) => {
						let imgurl = res.tempFilePaths[0]
						uni.uploadFile({
							//开发者服务器 url
							url: getApp().globalData.data.requestUrl + '/upload/chat',
							method: "POST",
							filePath: imgurl,
							fileType: 'image',
							name: 'image',
							header: {
								'token': uni.getStorageSync('token'),
								// 'Content-Type': 'application/x-www-form-urlencoded'  
							},
							formData: {
								accept: 'image',
								room_id: that.room_id
							},
							success: (file) => {
								console.log(file)
								let info = JSON.parse(file.data)
								console.log(info);
								if (info.status == 1) {
									sendMsg({
										room_id: that.room_id,
										type: 2,
										img: info.data.path,
									}).then(res => {
										if (res.status == 1) {
											let data = res.data
											that.chatList.push(data)
											setTimeout(() => {
												that.scrollView = 'tab' + res.data
													.id
												// that.setPageScrollTo(`#${that.scrollView}`)
												uni.pageScrollTo({
													duration: 100,
													selector: `#${that.scrollView}`,
													success() {
														console.log(
															'滚动成功');
													},
													fail(err) {
														console.log(
															'滚动失败');
													}
												})
											}, 100)
											let sendData = JSON.parse(JSON.stringify(res
												.data))
											sendData.say_type = 2
											that.sendSocket("send", {
												type: 2,
												content: sendData,
												room_id: that.room_id
											})

											// this.getHeight()
										} else {
											uni.$showMsg(res.message)
										}
									})
								} else {
									uni.$showMsg(info.message)
								}

							}

						})
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: #f7f7f7;
	}

	.more_text {
		text-align: center;
		margin-bottom: 16px;
		font-size: 12px
	}

	.more {
		text-align: center;
		padding-bottom: 10px;
	}

	.chatscroll {
		// height: calc(100vh - 104px);
		height: auto !important;
		overflow-y: scroll;
		padding-bottom: 50px;

		&::-webkit-scrollbar {
			display: none;
			/* Chrome Safari */
		}
	}

	.sendmsg {
		position: fixed;
		width: 100%;
		background: #fff;
		min-height: 40px;
		bottom: 0;
		/* #ifdef H5 */
		bottom: 0;
		/* #endif */
		padding: 5px 0;
		box-sizing: border-box;
		line-height: 20px;

		.top {
			align-items: flex-end;
			display: flex;
			box-sizing: border-box;
			width: 100%;
			padding: 0 10px;
		}

		.emoji {
			width: 100%;
			background: #fff;
		}

		textarea {
			background: #efefef;
			flex: 1;
			padding: 8px;
			border-radius: 5px;
			max-height: 72px;
			height: auto;
			box-sizing: border-box;
		}

		.imgbox {
			height: 40px;
			display: flex;
			align-items: center;
		}

		image {
			width: 30px;
			margin-left: 10px;
			transition: .5;
		}

		.emo {
			image {
				margin-left: 0;
				margin-right: 10px;
			}
		}

		text {
			margin-left: 10px;
			background: #0a9413;
			color: #fff;
			height: 37px;
			width: 65px;
			display: flex;
			justify-content: center;
			align-items: center;
			box-sizing: border-box;
			border-radius: 5px;
			transition: .5;
		}
	}

	.chatlist {
		padding-top: 10px;
	}

	.chatitem {
		padding: 0 10px;
		margin-bottom: 15px;

		.headerimg {
			margin-top: 5px;
			width: 35px;
			height: 35px;
			border-radius: 5px;
			float: left;
		}

		.item-info {
			width: calc(90vw - 55px);
			padding-left: 10px;
			float: left;

			.name {
				color: #777;
				font-size: 12px;
				margin-bottom: 3px;

				text {
					margin-left: 5px;
				}
			}

			.item-msg {
				max-width: 100%;
				font-size: 14px;
				float: left;

				text {
					padding: 5px 10px;
					border-radius: 5px;
					background: #fff;
					display: block;
				}
			}

			.item-imgbox {
				height: 100%;
				height: 180px;

				image {
					// width: 50%;
					// max-width: 70%;
					height: 100%;
					max-height: 100px;
				}
			}
		}
	}

	.chatitem::after {
		content: '';
		display: block;
		height: 0;
		clear: both;
		visibility: hidden;
	}

	.mychat {
		.headerimg {
			float: right;
		}

		.item-info {
			float: right;
			padding-left: 0;
			padding-right: 10px;

			.name {
				text-align: right;
			}

			.item-msg {
				float: right;
			}

			.item-imgbox {
				text-align: right;
			}

		}
	}
</style>